package com.luoxue.mito.config.handler;

import com.luoxue.mito.common.ResultBody;
import org.springframework.core.MethodParameter;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ServerResponseAdvice implements ResponseBodyAdvice<Object> {
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultBody globalException(Exception e) {
        e.printStackTrace();
        return ResultBody.error(e.getMessage());
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ResultBody) {
            return body;
        } else if (body instanceof RepresentationModel) {
            return RepresentationModel.of(ResultBody.ok(body));
        }
        return ResultBody.ok(body);
    }
}
